package com.pfzy.liveeventbusdemo.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus
import com.pfzy.liveeventbusdemo.LiveEventBusDemo
import com.pfzy.liveeventbusdemo.R
import com.pfzy.liveeventbusdemo.databinding.ActivityStickyDemoBinding

/**
 * 粘性
 */
class StickyActivity : AppCompatActivity() {
    private var binding: ActivityStickyDemoBinding? = null
    private val observer: Observer<String> =
        Observer { s -> binding?.tvSticky2?.text = "observeStickyForever注册的观察者收到消息: $s" }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_sticky_demo)
        binding?.lifecycleOwner = this

        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_STICKY, String::class.java)
            .observeSticky(this,
                { s -> binding?.tvSticky1?.text = "observeSticky注册的观察者收到消息: $s" })

        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_STICKY, String::class.java)
            .observeStickyForever(observer)
    }

    override fun onDestroy() {
        super.onDestroy()
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_STICKY, String::class.java)
            .removeObserver(observer)
    }
}